/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.anhndt.audiobook.business;

import com.anhndt.audiobook.iface.ProcessListener;
import com.anhndt.audiobook.utils.Util;
import com.anhndt.audiobook.utils.StringUtil;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.IOException;
import javax.microedition.io.Connector;
import javax.microedition.io.ContentConnection;

/**
 *
 * @author Anhndt
 */
public class AudioDownloadManager {

    public static final int SIZE_BLOCK = 256 * 1024;
    public static final int SIZE_HEADER = 128;
    private String url;
    protected ProcessListener listener;
    protected boolean loadding = true;
    private long fileSize;
    private int lengthDataDownloaded;
    private int indexBlock = -1;
    private int maxBlock;
    DataInputStream iStrm = null;
    ContentConnection connection;

    public AudioDownloadManager(String url, long fileSize, ProcessListener listener) {
        this.url = Util.getUrl(url);
        this.fileSize = fileSize;
        this.maxBlock = Util.divRounded2(fileSize - SIZE_HEADER, SIZE_BLOCK);
        this.listener = listener;
        try {
            connection = (ContentConnection) Connector.open(url);
            iStrm = connection.openDataInputStream();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public boolean isLoading() {
        return loadding;
    }

    public synchronized void start() {
        loadding = true;
    }

    public synchronized void stop() {
        loadding = false;
    }
    
    public void release() {
        loadding = false;
        try {
            if(connection != null) {
                connection.close();
            }
            if(iStrm != null) {
                iStrm.close();
            }
        }catch(Exception e){}
    }

    public void setListener(ProcessListener listener) {
        this.listener = listener;
    }

    public boolean isFinished() {
        return fileSize <= lengthDataDownloaded;
    }

    public void startLoadBlock(final int counterBlock) {
        new Thread() {

            public void run() {
                try {
                    for (int i = 0; i < counterBlock; i++) {
                        byte[] data = loadBLock(SIZE_BLOCK);
                        if (listener != null && data != null) {
                            listener.onSuccess(data, indexBlock);
                        }
                    }
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }.start();
    }

    public void loadHeader() throws IOException {
        new Thread() {

            public void run() {
                try {
                    byte[] header = loadBLock(SIZE_HEADER);
                    if (listener != null && header != null) {
                        listener.onSuccess(header, -1);
                    }
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }.start();

    }

    private byte[] loadBLock(int blockSize) throws IOException {
        if (StringUtil.isNullOrEmpty(url) || iStrm == null) {
            return null;
        }
        System.out.println(" ------------------ START  [Downloading] indexBlock =  " + indexBlock);
        ByteArrayOutputStream bStrm = null;
        byte dataBlock[] = null;
        try {
            bStrm = new ByteArrayOutputStream();
            int ch;
            int lengthBlock = 0;
            while ((ch = iStrm.read()) != -1) {
                if (!loadding) {
                    System.out.println("ko load audio nua");
                    dataBlock = null;
                    return null;
                }
                bStrm.write(ch);
                lengthBlock++;
                if (blockSize <= lengthBlock) {
                    break;
                }
            }
            dataBlock = bStrm.toByteArray();
            if (dataBlock != null) {
                System.out.println(" ------------------ START  [SUCCESSFUL] length = " + dataBlock.length + "      indexBlock =  " + indexBlock);
                indexBlock++;
                int lenght = dataBlock.length / 1024;
                Util.incrementData(lenght);
            }
            return dataBlock;
        } catch (Exception e) {
        } finally {
            if (bStrm != null) {
                bStrm.close();
            }
        }
        return dataBlock;
    }
}
